<!--
 * @Date:
 * @Author:
 * @LastEditTime:
 * @FilePath:
 * @pageName: 这是--(新建库存调拨单)--页面
-->
<template>
    <div>
      <Navbar :appTitle="appTitle" />
      <div
        class="search-content wrap-apply"
        :style="{
          top: GLOBAL.currentEnvironment ? '0' : '',
          height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',
          paddingBottom: GLOBAL.currentEnvironment ? '0.66rem' : '',
        }"
      >
        <van-cell-group style="margin-top: 0.1rem">
          <p class="label required FormTit"><span></span>调拨单号</p>
          <div class="haveUnitBox">
            <van-field
              v-model="buildForm.allotOrder"
              :maxLength="17"
              placeholder="请输入"
              @blur="checkInputValue(buildForm.allotOrder)"
            />
            <span class="btn-text" @click="genEntityCode">自动生成</span>
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>调拨日期</p>
          <van-field
            is-link
            readonly
            name="picker"
            v-model="buildForm.allotTime"
            @click="timePickShow = true"
            placeholder="请选择"
          >
          </van-field>
          <div class="bottomLine" style="margin: 0.01rem 0.16rem"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label required FormTit"><span></span>调出仓库</p>
          <van-field-select-picker
            label=""
            placeholder="请选择"
            v-model="buildForm.outWarehouseId"
            :columns="stockList"
            :clickType="'outStock'"
            :option="{ label: 'text', value: 'value' }"
            @confirm="sureWare"
            @prePopShow="showBefore"
          />
          <div class="bottomLine"></div>
        </van-cell-group>
  
        <van-cell-group>
          <p class="label required FormTit"><span></span>调入仓库</p>
          <van-field-select-picker
            label=""
            placeholder="请选择"
            v-model="buildForm.inWarehouseId"
            :columns="stockList"
            :clickType="'inStock'"
            :option="{ label: 'text', value: 'value' }"
            @confirm="sureInWareHouse($event)"
            @prePopShow="showBefore"
          />
          <div class="bottomLine"></div>
        </van-cell-group>
  
        <van-cell-group>
          <p class="label required FormTit"><span></span>调拨明细记录方式</p>
          <van-field-select-picker
            label=""
            placeholder="调拨单生效后，自动生成出库记录、入库记录"
            v-model="buildForm.type"
            :columns="outInStockTypeList"
            :option="{ label: 'text', value: 'value' }"
          />
          <div class="bottomLine" style="margin-top: 0.01rem"></div>
        </van-cell-group>
        <van-cell-group>
          <p class="label">调拨原因</p>
          <van-field
            v-model="buildForm.reason"
            rows="2"
            autosize
            label=""
            type="textarea"
            maxlength="500"
            placeholder="请输入"
            show-word-limit
          />
        </van-cell-group>
  
        <van-cell-group
          style="margin-top: 0.1rem"
          v-if="commodityList.length === 0"
        >
          <div class="goodTitleBox">
            <div class="label otherText">调拨明细</div>
          </div>
          <div class="bottomLine"></div>
        </van-cell-group>
        <div
          class="reportBox"
          v-for="(item, index) in commodityList"
          :key="index"
        >
          <van-cell-group style="margin-top: 0.1rem">
            <div class="goodTitleBox">
              <div class="label otherText">调拨明细({{ index + 1 }})</div>
              <img
                class="buleDelete"
                @click="deleteGodd(index)"
                src="@/assets/img/delete.png"
                alt=""
              />
            </div>
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>物品编号|物品名称</p>
            <van-field-select-picker
              :supportClear="true"
              label=""
              placeholder="请选择"
              v-model="item.goodsId"
              :columns="stockGoodList"
              :option="{ label: 'goodText', value: 'goodsId' }"
              @confirm="sureGood($event, item)"
              @prePopShow="showBefore"
            />
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>规格</p>
            <van-field v-model="item.spec" disabled placeholder="请选择" />
            <div class="bottomLine" style="margin-top: 0.01rem"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>批次编号</p>
            <!-- <van-field
              v-model="item.goodsBatchCode"
              disabled
              placeholder="请选择"
            /> -->
            <van-field-select-picker
              :supportClear="true"
              label=""
              placeholder="请选择"
              v-model="item.goodsBatchNumber"
              :columns="item.goodsBatchList"
              :option="{ label: 'goodsBatchCode', value: 'goodsBatchNumber' }"
              @confirm="sureGoodBatch($event, item)"
              @prePopShow="showBefore"
            />
            <div class="bottomLine" style="margin-top: 0.01rem"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>调出库区</p>
            <van-field-select-picker
              label=""
              placeholder="请先选择调出库区"
              v-model="item.outWarehouseArea"
              :columns="item.areas"
              :option="{ label: 'areaName', value: 'areaId' }"
              @confirm="sureGoodBatchArea($event, item, index)"
              @prePopShow="showBefore"
            />
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>调出库位</p>
            <van-field-select-picker
              label=""
              placeholder="请先选择调出库位"
              v-model="item.outWarehouseLocation"
              :columns="item.location"
              :clickType="'outLocation'"
              :option="{ label: 'locationName', value: 'locationId' }"
              @confirm="sureWareLocation($event, item)"
              @prePopShow="showBefore"
            />
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>调入库区</p>
            <van-field-select-picker
              label=""
              placeholder="请先选择调入仓库"
              v-model="item.inWarehouseArea"
              :columns="inStockLocationList"
              :clickType="'inArea'"
              :option="{ label: 'areaName', value: 'areaId' }"
              @confirm="sureInGoodBatchArea($event, item)"
              @prePopShow="showBefore"
            />
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit"><span></span>调入库位</p>
            <van-field-select-picker
              label=""
              placeholder="请先选择调入库区"
              v-model="item.inWarehouseLocation"
              :columns="item.inLocation"
              :clickType="'inLocation'"
              :option="{ label: 'locationName', value: 'locationId' }"
              @confirm="sureInWareLocation"
              @prePopShow="showBefore"
            />
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit">
              <span></span>调拨基本单位数量（合格品）
            </p>
            <van-field
              v-model="item.qualifiedNum"
              @input="inputNum(item.qualifiedNum, item, 'qualifiedNum')"
              placeholder="请输入"
            >
              <template slot="right-icon">
                <span>
                  <van-dropdown-menu active-color="#1890ff">
                    <van-dropdown-item
                      v-model="item.selectUnitQ"
                      :options="unitOpyions(item.unitList)"
                      @change="
                        (v) =>
                          changeNumUnit(
                            v,
                            item,
                            'selectUnitQ',
                            'rateQ',
                            'qualifiedNum'
                          )
                      "
                    />
                  </van-dropdown-menu>
                </span>
              </template>
            </van-field>
            <div class="bottomLine"></div>
          </van-cell-group>
          <van-cell-group>
            <p class="label required FormTit">
              <span></span>调拨基本单位数量（报废品）
            </p>
            <van-field
              v-model="item.scrapNum"
              placeholder="请输入"
              @input="inputNum(item.scrapNum, item, 'scrapNum')"
            >
              <template slot="right-icon">
                <span>
                  <van-dropdown-menu active-color="#1890ff">
                    <van-dropdown-item
                      v-model="item.selectUnitS"
                      :options="unitOpyions(item.unitList)"
                      @change="
                        (v) =>
                          changeNumUnit(
                            v,
                            item,
                            'selectUnitS',
                            'rateS',
                            'scrapNum'
                          )
                      "
                    />
                  </van-dropdown-menu>
                </span>
              </template>
            </van-field>
            <div class="bottomLine"></div>
          </van-cell-group>
        </div>
        <van-cell-group>
          <!-- <div class="addBtnBox" @click="copyGood(item, index)">+复制</div> -->
          <div class="addBtnBox" @click="addGood">+添加</div>
        </van-cell-group>
        <van-cell-group style="margin-top: 0.1rem">
          <upload
            iconType="fj"
            @fileChange="fileChange"
            :fileIds="buildForm.dingFileInfo"
          />
        </van-cell-group>
        <div style="margin-top: 0.12rem" v-if="showExam">
          <Examine
            @submitProcess="submitProcess"
            @getUserState="getUserState"
            type="0"
            :key="examKey"
            id="WMS_STOCK_ALLOT"
            ref="examine"
          />
          <div style="height: 0.26rem"></div>
        </div>
        <div class="search-bottoms">
          <!--        <van-button-->
          <!--            type="info"-->
          <!--            plain-->
          <!--            :loading="loadingDraft"-->
          <!--            class="btncancel"-->
          <!--            loading-text="暂存中..."-->
          <!--            @click="submitDraft"-->
          <!--        >暂存</van-button-->
          <!--        >-->
          <van-button
            type="info"
            :loading="loadingSubmit"
            class="btnconfirm"
            loading-text="提交中..."
            @click="handleBtnConfirm"
            >提交
          </van-button>
        </div>
      </div>
      <!--选择入库日期 -->
      <van-popup v-model="timePickShow" position="bottom">
        <van-datetime-picker
          @confirm="confirmPick"
          v-model="inStockTime"
          @cancel="cancelPick"
          type="date"
          title="开始时间"
          :formatter="formatter"
        />
      </van-popup>
      <goods-picker
        v-if="showGoodsPicker"
        :listUrl="listUrl"
        @getCheckedGoods="getCheckedGoods"
      ></goods-picker>
    </div>
  </template>
  <script>
  import { getAction } from "@/api/manage";
  import upload from "@/components/upload/upload";
  import {
    clearNoNum,
    validateDuplicateValue,
    accAdd,
    accMul,
    accDivMin,
  } from "@/utils/util";
  import Navbar from "@/components/navBar/navBar_right";
  import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
  import { APILX } from "@/api/requestLx";
  import {
    pmDraftSave,
    pmDraftGet,
    pmDraftDel,
    wmsWarehouseQueryByIdIsExist,
    goodsQueryByIdIsExist,
    stockLatticeApi,
    stockAllotAdd,
    getWarehouseListByGoodsId,
  } from "@/api/mobile";
  import GoodsPicker from "@/components/choiceuse/GoodsPicker";
  import {
    stockListApi,
    stockAreaApi,
    inStockGoodApi,
    batchStockApi,
    OutInBoundTypeApi,
    findUnitListByGoodsIdSync,
    getWarehouseGoodsList,
    findAreaAndLocationByGoodsAndBatch,
    findGoodsBatchListByWareHouseId,
    findAreaByGoodsAndBatch,
    findLocationByGoodsAndBatch,
    wmsWarehouseOperateGetArea,
    wmsWarehouseOperateGetLocation,
  } from "@/api/mobile";
  import moment from "moment";
  import Examine from "@/components/examine";
  
  export default {
    name: "search",
    components: {
      VanFieldSelectPicker,
      Navbar,
      upload,
      GoodsPicker,
      Examine,
    },
    beforeRouteLeave(to, from, next) {
      if (this.showPeopleSlect) {
        this.$refs.examine.closePicker();
        next(false);
      } else {
        next();
      }
    },
    data() {
      return {
        //商品数据
        commodityList: [
          // {
          //   goodsId: "",
          //   spec: "",
          //   assistUnit: "",
          //   qualifiedNum: "",
          //   scrapNum: "",
          // },
        ],
        buildForm: {
          allotOrder: "",
          operateUserId: "",
          allotTime: "",
          outWarehouseId: "", // 调出仓库
          outWarehouseAreaId: "", // 调出库区
          outWarehouseLocationId: "", // 调出库位
          inWarehouseId: "", // 调入仓库
          inWarehouseAreaId: "", // 调入库区
          inWarehouseLocationId: "", // 调入库位
          reason: "",
          complete: false,
          dingFileInfo: "",
          operateType: "1",
          type: "automatic_generation",
          operateTaskType: "",
        },
        showPeopleSlect: false,
        examKey: 2,
        showExam: true,
        timePickShow: false,
        stockList: [], // 仓库列表
        stockAreaList: [], // 库区列表
        inStockAreaList: [], // 入库库区列表
        stockLocationList: [], // 库位列表
        inStockLocationList: [], // 入库库位列表
        stockGoodList: [],
        inStockTime: new Date(),
        outInStockTypeList: [
          {
            text: "调拨单生效后，自动生成出库记录、入库记录",
            title: "调拨单生效后，自动生成出库记录、入库记录",
            value: "automatic_generation",
          },
          {
            text: "调拨后在出入库查询中手动新建出库单、入库单",
            value: "manual_generation",
          },
        ],
        loadingSubmit: false,
        loadingDraft: false,
        showGoodsPicker: false,
        appTitle: this.$route.meta.title,
        // listUrl: "/wms/goods/getAllGoodsBaseInfo",
      };
    },
    computed: {},
    beforeRouteLeave(to, from, next) {
      if (this.showGoodsPicker) {
        this.appTitle = this.$route.meta.title;
        this.showGoodsPicker = false;
        next(false);
      } else {
        next();
      }
    },
    async mounted() {
      if (this.$route.query.formPage == "scanCode" && this.$route.query.code) {
        APILX.goodsQueryById(this.$route.query.code.id).then(async (res) => {
          if (res.code == 200) {
            // 获取有该物品的仓库
            const wareHouseRes = await getWarehouseListByGoodsId({
              goodsId: this.$route.query.code.id,
            });
            const wareHouseId = wareHouseRes.result[0].value;
            this.buildForm.outWarehouseId = wareHouseId;
            this.listUrl = `/wms/wmsWarehouseOperate/getWarehouseGoodsList?warehouseId=${wareHouseId}`;
            this.stockList = wareHouseRes.result;
  
            let good = {};
  
            // 查询仓库下的物品
            getAction("/wms/wmsWarehouseOperate/getWarehouseGoodsList", {
              keyword: res.result.goodsCode,
              warehouseId: wareHouseId,
            }).then(async (res2) => {
              if (res2.code == 200) {
                this.stockGoodList = res2.result.records;
                for (let item of this.stockGoodList) {
                  item.goodText = `${item.goodsCode}|${item.goodsName}`;
                }
  
                let arr = res2.result.records.filter(
                  (item) => item.goodsCode == res.result.goodsCode
                );
                good = arr[0];
  
                // 获取第一个仓库和当前物品下的批次
                const findGoodsBatchList = await findGoodsBatchListByWareHouseId({
                  goodsId: good.goodsId,
                  wareHouseId: wareHouseId,
                });
                let newArr = {
                  unitList: JSON.stringify([]),
                  goodsBatchList: findGoodsBatchList.result,
                  rateQ: 1,
                  rateS: 1,
                  rateQOld: 1,
                  rateSOld: 1,
  
                  goodsId: good.goodsId,
                  goodsCode: good.goodsCode,
                  goodsName: good.goodsName,
                  spec: good.spec,
                  assistUnit: good.assistUnit,
                  kcGoodsQualifiedNum: good.kcGoodsQualifiedNum,
                  kcGoodsScrapNum: good.kcGoodsScrapNum,
                  disabled: true,
                  scrapNum: "0",
                  qualifiedNum: "0",
                };
                this.commodityList = this.commodityList.concat(newArr);
              }
            });
          }
        });
      }
    },
    created() {
      let user = localStorage.getItem("pro__Login_Userinfo");
      pmDraftGet({
        entityType: "WMS_STOCK_ALLOT",
      }).then((res) => {
        if (res.result && res.result.isDraft) {
          this.$nextTick(() => {
            this.checkFormInfoAsync(res.result.editable, res.result.form);
          });
        } else {
          this.buildForm.operateUserId = JSON.parse(user).value.id;
          // this.buildForm.allotTime = moment(new Date()).format("YYYY-MM-DD");
        }
      });
      this.getInitData();
      // this.getStockGood();
    },
    methods: {
      getUserState(v) {
        this.showPeopleSlect = v;
      },
      submitProcess(e) {
        if (e && e.nodeDtos) {
          // 获取到数据后写表单提交的方法
          this.buildForm.processDataVo = e;
          this.btnConfirm();
        } else {
          // 调用子组件的方法获取数据
          this.$refs.examine.confirm();
        }
      },
      getInitData() {
        this.getInStockList(); // 仓库列表
        this.getStockAreaList(); // 库区列表
        this.getStockLatticeList(); // 库位列表
      },
      // 库位下拉 stockLatticeApi
      getStockLatticeList() {
        stockLatticeApi().then((res) => {
          if (res.success) {
            this.stockLocationList = res.result.map((item) => {
              return {
                text: item.name,
                title: item.name,
                value: item.code,
              };
            });
          } else {
            this.$toast(res.message);
          }
        });
      },
      // 库区下拉
      getStockAreaList() {
        stockAreaApi().then((res) => {
          if (res.success) {
            this.stockAreaList = res.result.map((item) => {
              return {
                text: item.name,
                title: item.name,
                value: item.code,
              };
            });
          } else {
            this.$toast(res.message);
          }
        });
      },
      // 仓库下拉
      getInStockList() {
        stockListApi().then((res) => {
          if (res.success) {
            this.stockList = res.result;
          } else {
            this.$toast(res.message);
          }
        });
        // OutInBoundTypeApi({type: "I", blackTypeIds: "I8"}).then((res) => {
        //   this.outInStockTypeList = res.result;
        // });
      },
      changeNumUnit(v, item, key, rate, inputKey) {
        let unitList = JSON.parse(item.unitList);
        let unit = unitList.find((u) => u.id == v);
        let old_num = item[inputKey]
          ? accMul(item[inputKey], item[`${rate}Old`])
          : ""; /* 当前数值乘以单位换算比例，得到对应的基本单位数量 */
        item[key] = v;
        item[rate] = unit.conversionRate;
        item[`${rate}Old`] = unit.conversionRate;
        item[inputKey] = item[inputKey]
          ? accDivMin(old_num, unit.conversionRate)
          : "0"; /* 基本单位数量除以辅助单位比例，得到当前数值对应辅助单位数量 */
      },
      unitOpyions(v) {
        let list = JSON.parse(v);
        let val = list.map((item) => {
          item.value = item.id;
          item.text = item.unit;
          return item;
        });
        return val;
      },
      /* 表单中部分数据受外部影响，可能被删除或已被使用，回显暂存数据时先校验，被影响的数据直接清除或清0 */
      async checkFormInfoAsync(list, form) {
        let that = this;
        /* 校验物品是否存在 ---begin--- */
        let goodsList = list;
        for (let i = 0; i < goodsList.length; i++) {
          const item = goodsList[i];
          const goodsIsExist = await goodsQueryByIdIsExist({ id: item.goodsId });
          if (!goodsIsExist) {
            goodsList.splice(i, 1);
          } else {
            // 物品单位是否变化,如果被删就默认选定基本单位，辅助单位的转换比例在这里更新为最新转换比例
            const unitRes = await findUnitListByGoodsIdSync({
              goodsId: item.goodsId,
            });
            let selectUnitQVal = unitRes.result.find(
              (u) => u.id == item.selectUnitQ
            );
            let selectUnitSVal = unitRes.result.find(
              (u) => u.id == item.selectUnitS
            );
            item.unitList = JSON.stringify(unitRes.result);
            if (!selectUnitQVal) {
              item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id;
              item.rateQ = 1;
              item.rateQOld = 1;
              item.qualifiedNum = "0";
            } else {
              item.rateQ = selectUnitQVal.conversionRate;
              item.rateQOld = selectUnitQVal.conversionRate;
            }
            if (!selectUnitSVal) {
              item.selectUnitS = unitRes.result[unitRes.result.length - 1].id;
              item.rateS = 1;
              item.rateSOld = 1;
              item.scrapNum = "0";
            } else {
              item.rateS = selectUnitSVal.conversionRate;
              item.rateSOld = selectUnitSVal.conversionRate;
            }
  
            let goodInfo = goodsIsExist.result;
            item.spec = goodInfo.spec;
            item.assistUnit = goodInfo.assistUnit;
            item.goodsCode = goodInfo.goodsCode;
            item.goodsName = goodInfo.goodsName;
          }
        }
        that.commodityList = goodsList;
        /* 校验物品是否存在 ---end--- */
  
        /* 校验仓库、入库类型是否存在 ---begin--- */
        const warehouseIsExist = await wmsWarehouseQueryByIdIsExist({
          id: form.warehouseId,
        });
        if (!warehouseIsExist) {
          form.warehouseId = undefined;
        }
        OutInBoundTypeApi({ type: "I", blackTypeIds: "I8" }).then((res) => {
          let types = res.result;
          let type = types.find((item) => item.value == form.operateTaskType);
          if (!type) {
            form.operateTaskType = undefined;
          }
        });
        this.buildForm = form;
        // this.buildForm.allotTime = form.allotTime
        //     ? moment(form.allotTime).format("YYYY-MM-DD")
        //     : ""; // 兼容PC端暂存
        /* 校验仓库、入库类型是否存在 ---end--- */
      },
      deleteGodd(index) {
        this.commodityList.splice(index, 1);
      },
      // copyGood(item, index) {
      //   console.log(item, index);
  
      //   this.commodityList.splice(index + 1, 0, {
      //     ...item,
      //     warehouseLocationId: "",
      //     goodsQualifiedNum: "",
      //     goodsScrapNum: "",
      //   });
      // },
      addGood() {
        this.showGoodsPicker = true;
        this.appTitle = "选择物品";
      },
      genEntityCode() {
        getAction("/sys/common/genEntityCode", {
          entityCode: "WMS_STOCK_ALLOT",
        }).then((res) => {
          if (res.code == 200) {
            this.buildForm.allotOrder = res.result;
          } else {
            this.buildForm.allotOrder = "";
            this.$toast(res.message);
          }
        });
      },
      fileChange(ids) {
        this.buildForm.dingFileInfo = ids;
        console.log("父组件" + ids); //你要保存的fileids
      },
      handleBtnConfirm() {
        this.submitProcess();
      },
      // 提交
      btnConfirm(e) {
        if (!this.buildForm.allotOrder) {
          this.$toast(`请输入调拨单号`);
          return;
        }
        if (!this.buildForm.allotTime) {
          this.$toast(`请选择调拨日期`);
          return;
        }
        if (!this.buildForm.outWarehouseId) {
          this.$toast(`请选择出库仓库`);
          return;
        }
        if (!this.buildForm.inWarehouseId) {
          this.$toast(`请选择入库仓库`);
          return;
        }
        if (!this.buildForm.type) {
          this.$toast(`请选择调拨明细记录方式`);
          return;
        }
        let goodsList = [];
        for (let i = 0; i < this.commodityList.length; i++) {
          let item = this.commodityList[i];
          if (!item.goodsId) {
            this.$toast(`调拨明细（${i + 1}），请选择商品`);
            return;
          }
          if (item.qualifiedNum == "") {
            this.$toast(`调拨明细（${i + 1}），请输入合格品数`);
            return;
          }
          if (item.scrapNum == "") {
            this.$toast(`调拨明细（${i + 1}），请输入报废品数`);
            return;
          }
          let goodsNum = accAdd(Number(item.qualifiedNum), Number(item.scrapNum));
          if (goodsNum == 0) {
            this.$toast(
              `调拨明细（${i + 1}），输入的合格品数与报废品数之和必须大于0`
            );
            return;
          }
          let obj = { ...item };
          obj.goodsId = item.goodsId;
          obj.qualifiedNum = accMul(item.qualifiedNum, item.rateQ);
          obj.scrapNum = accMul(item.scrapNum, item.rateS);
          obj.goodsNum = accAdd(Number(obj.qualifiedNum), Number(obj.scrapNum));
          goodsList.push(obj);
        }
  
        let params = {
          processDataVo: { nodeDtos: [] },
  
          ...this.buildForm,
          applyNo: this.buildForm.allotOrder,
          // goodsList,
          stockAllotGoodDetailList: [...goodsList],
        };
        params.allotTime = moment(params.allotTime).format("YYYY-MM-DD");
        this.loadingSubmit = true;
        this.handleSubmit(params);
      },
  
      handleSubmit(params) {
        stockAllotAdd(params).then((res) => {
          if (res.success) {
            this.$toast(res.result);
            pmDraftDel({ entityType: "WMS_STOCK_ALLOT" }).then((res) => {});
            this.$router.go(-1);
          } else {
            this.$toast(res.message);
          }
          this.loadingSubmit = false;
        })
      },
      submitDraft() {
        let draft = {
          form: this.buildForm,
          editable: this.commodityList,
          isDraft: true,
        };
        this.loadingDraft = true;
        pmDraftSave({
          draft,
          entityType: "WMS_STOCK_ALLOT",
        }).then((res) => {
          if (res.code == 200) {
            this.$toast(res.message);
            this.$router.go(-1);
          } else {
            this.$toast(res.message);
          }
          this.loadingDraft = false;
        });
      },
      checkInputValue(value) {
        validateDuplicateValue(
          "wms_warehouse_operate",
          "order_number",
          value,
          "",
          (res) => {
            if (res) {
              this.buildForm.allotOrder = "";
              this.$toast(res);
            }
          }
        );
      },
      inputNum(value, item, inputKey) {
        let newNum = clearNoNum(value);
        item[inputKey] = newNum;
      },
      async sureWare(itemWare) {
        if (
          this.$route.query.formPage == "scanCode" &&
          itemWare.value != this.buildForm.outWarehouseId
        ) {
          console.log(this.commodityList[0], "======---000000");
          this.commodityList[0].goodsBatchList = [];
          this.commodityList[0].goodsBatchNumber = "";
  
          const findGoodsBatchList = await findGoodsBatchListByWareHouseId({
            goodsId: this.commodityList[0].goodsId,
            wareHouseId: itemWare.value,
          });
          this.commodityList[0].goodsBatchList = findGoodsBatchList.result;
          this.$forceUpdate();
        }
        console.log("itemWare", itemWare);
        this.listUrl = `/wms/wmsWarehouseOperate/getWarehouseGoodsList?warehouseId=${itemWare.value}`;
        getWarehouseGoodsList({
          warehouseId: itemWare.value,
        }).then(({ result }) => {
          this.stockGoodList = result.records;
          for (let item of this.stockGoodList) {
            item.goodText = `${item.goodsCode}|${item.goodsName}`;
          }
        });
      },
      sureInWareHouse(inWareVal) {
        console.log(this.buildForm.outWarehouseId, inWareVal);
        let that = this;
        if (inWareVal.value === this.buildForm.outWarehouseId) {
          setTimeout(() => {
            that.buildForm.inWarehouseId = "";
          }, 500);
  
          this.$toast(`入库仓库不能与出库仓库相同`);
          return false;
        }
        wmsWarehouseOperateGetArea({
          warehouseId: inWareVal.value,
        }).then(({ result }) => {
          this.inStockLocationList = result;
          that.$forceUpdate();
        });
      },
      sureGoodBatch(select, item) {
        item.goodsBatchCode = select.goodsBatchCode;
        item.goodsBatchType = select.goodsBatchType;
        let that = this;
        findAreaByGoodsAndBatch({
          goodsId: item.goodsId,
          wareHouseId: this.buildForm.outWarehouseId,
          goodsBatchCode: select.goodsBatchCode,
          goodsBatchNumber: select.goodsBatchNumber,
        }).then((res) => {
          console.log(res);
          item.areas = res.result;
          that.$forceUpdate();
          console.log(this.commodityList);
        });
      },
      sureGoodBatchArea(select, item) {
        let that = this;
        findLocationByGoodsAndBatch({
          goodsId: item.goodsId,
          wareHouseId: this.buildForm.outWarehouseId,
          goodsBatchCode: item.goodsBatchCode,
          goodsBatchNumber: item.goodsBatchNumber,
          wareAreaId: select.areaId,
        }).then(({ result }) => {
          if (!result || result.length == 0) {
            that.$toast("没有调出库位");
            return false;
          }
          item.location = result || [];
          that.$forceUpdate();
        });
      },
      sureWareLocation() {},
  
      sureInGoodBatchArea(select, item) {
        let that = this;
        wmsWarehouseOperateGetLocation({
          wareHouseId: this.buildForm.inWarehouseId,
          wareAreaId: select.areaId,
        }).then(({ result }) => {
          if (!result || result.length == 0) {
            that.$toast("没有调入库位");
            return false;
          }
          item.inLocation = result || [];
          that.$forceUpdate();
        });
      },
      sureInWareLocation() {},
      async sureGood(selectGood, item) {
        const unitRes = await findUnitListByGoodsIdSync({
          goodsId: selectGood.goodsId,
        });
        item.unitList = JSON.stringify(unitRes.result);
        item.rateQ = 1;
        item.rateS = 1;
        item.rateQOld = 1;
        item.rateSOld = 1;
        item.selectUnitQ = unitRes.result[unitRes.result.length - 1].id;
        item.selectUnitS = unitRes.result[unitRes.result.length - 1].id;
  
        item.qualifiedNum = 0;
        item.scrapNum = 0;
        item.scrapNum = 0;
        item.spec = selectGood.spec;
        item.goodsBatchNumber = selectGood.goodsBatchNumber;
        item.goodsBatchCode = selectGood.goodsBatchCode;
        item.goodsCode = selectGood.goodsCode; // 兼容PC端暂存
        item.goodsName = selectGood.goodsName; // 兼容PC端暂存
        item.assistUnit = selectGood.assistUnit;
        item.kcGoodsScrapNum = selectGood.kcGoodsScrapNum;
        console.log(this.buildForm);
        const findGoodsBatchList = await findGoodsBatchListByWareHouseId({
          goodsId: item.goodsId,
          wareHouseId: this.buildForm.outWarehouseId,
        });
        item.goodsBatchList = findGoodsBatchList.result;
        // findAreaAndLocationByGoodsAndBatch({
        //   wareHouseId: this.buildForm.outWarehouseId,
        //   goodsBatchCode: item.goodsBatchCode,
        //   goodsBatchNumber: item.goodsBatchNumber,
        //   goodsId: item.goodsId,
        // }).then(({ result }) => {
        //   console.log("findAreaAndLocationByGoodsAndBatch", result);
        // });
      },
      async getCheckedGoods(list) {
        this.showGoodsPicker = false;
        this.appTitle = this.$route.meta.title;
        let newArr = [];
        let tips = "";
        /* 当前选择商品是否已存在列表中↓ */
        this.commodityList.forEach((val) => {
          list.forEach((son) => {
            if (val.goodsId == son.id) {
              tips += `${son.goodsName},`;
              console.log("有重复", tips, son.goodsName);
              son.delete = true;
            }
          });
        });
        /* 若已存在列表中，则删除商品，不参与新增↓ */
        for (let i = 0; i < list.length; i++) {
          const good = list[i];
          const findGoodsBatchList = await findGoodsBatchListByWareHouseId({
            goodsId: good.goodsId,
            wareHouseId: this.buildForm.outWarehouseId,
          });
          console.log(findGoodsBatchList);
          if (!good.delete) {
            newArr.push({
              unitList: JSON.stringify([]),
              goodsBatchList: findGoodsBatchList.result,
              rateQ: 1,
              rateS: 1,
              rateQOld: 1,
              rateSOld: 1,
              // selectUnitQ: unitRes.result[unitRes.result.length - 1].id,
              // selectUnitS: unitRes.result[unitRes.result.length - 1].id,
  
              goodsId: good.goodsId,
              spec: good.spec,
              assistUnit: good.assistUnit,
              kcGoodsQualifiedNum: good.kcGoodsQualifiedNum,
              kcGoodsScrapNum: good.kcGoodsScrapNum,
              goodsCode: good.goodsCode,
              goodsName: good.goodsName,
              scrapNum: "0",
              qualifiedNum: "0",
            });
          }
        }
        if (newArr.length > 0) {
          this.commodityList = this.commodityList.concat(newArr);
          if (tips != "") {
            this.$toast(`物品：${tips}已存在，请直接修改数据`);
          }
        } else {
          if (tips != "") {
            this.$toast(`物品：${tips}已存在，请直接修改数据`);
          }
        }
        console.log(this.commodityList);
        console.log("拿到的商品数据：", list);
      },
      showBefore(callback) {},
  
      getStockGood(value) {
        let obj = {
          warehouseId: value,
        };
        inStockGoodApi(obj).then((res) => {
          if (res.success) {
            this.stockGoodList = res.result;
            for (let item of this.stockGoodList) {
              item.goodText = `${item.goodsCode}|${item.goodsName}`;
            }
          } else {
            this.$toast(res.message);
          }
        });
      },
  
      formatter(type, val) {
        if (type === "year") {
          return val + "年";
        }
        if (type === "month") {
          return val + "月";
        }
        if (type === "day") {
          return val + "日";
        }
        if (type === "hour") {
          return val + "时";
        }
        if (type === "minute") {
          return val + "分";
        }
        return val;
      },
      // 确定选择调拨日期
      confirmPick(date) {
        this.buildForm.allotTime = moment(date).format("YYYY-MM-DD");
        this.timePickShow = false;
      },
      // 取消选择时间
      cancelPick() {
        this.timePickShow = false;
      },
    },
  };
  </script>
  <style lang="scss" scoped>
  @import "@/assets/theme.scss";
  @import "@/views/workManagement/materialRequisition/materialForm.scss";
  
  /deep/ .van-dropdown-menu__bar {
    height: auto;
    box-shadow: none;
  }
  
  .search-content {
    //  padding-bottom: 0.5rem;
    position: fixed;
    top: 0.42rem;
    width: 100%;
    height: calc(100vh - 1rem);
    background: #f5f5f5;
    overflow: scroll;
    z-index: 99;
  
    .formgroup {
      background: #ffffff;
      // padding: 0 0.16rem;
      margin-top: 0.1rem;
      margin-bottom: 0.2rem;
      padding-top: 0.1rem;
  
      .title {
        width: 0.58rem;
        height: 0.14rem;
        font-size: 0.15rem;
        font-family: PingFang SC;
        font-weight: 400;
        color: #191f25;
        line-height: 0.05rem;
        margin-left: 0.16rem;
      }
    }
  
    .search-bottoms {
      width: 100%;
      height: 0.5rem;
      background: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      position: fixed;
      bottom: 0px;
      padding: 0rem 0.11rem;
      box-sizing: border-box;
      font-size: 0.16rem;
      font-weight: 500;
      z-index: 9;
  
      .btncancel {
        flex: 1;
        background: #f6f6f6;
        // border: 0.01rem solid rgba(25, 31, 37, 0.12);
        box-sizing: border-box;
        height: 0.39rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 0.03rem;
        margin-right: 0.11rem;
        color: #1890ff;
      }
  
      .btnconfirm {
        flex: 1;
        background: #1890ff;
        box-sizing: border-box;
        height: 0.39rem;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 0.03rem;
        color: #ffffff;
      }
    }
  }
  
  .bottomLine {
    height: 0.01rem;
    background-color: #f0f0f0;
    margin: 0 0.16rem;
  }
  
  .otherText {
    font-size: 0.16rem;
    font-weight: bold;
    color: #191f25;
  }
  
  .haveUnitBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding-right: 0.16rem;
  
    /deep/ .van-cell {
      padding-right: 0;
      width: 2.6rem;
    }
  
    /deep/ .van-field__control {
      max-width: 3rem;
    }
  }
  
  /deep/ .van-nav-bar {
    z-index: 99;
  }
  </style>
  